package com.ee.bruscar.configuration.maker;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.ee.bruscar.exceptions.BruscarException;
import com.ee.bruscar.util.reflection.TypeChecker;

public class DefaultMaker implements Maker
{
	Class<?> clazz;
	
	public DefaultMaker(Class<?> clazz)
	{
		this.clazz = clazz;
	}

	@SuppressWarnings("unchecked")
	public Object make()
	{
		try
		{
			Object instance = clazz.newInstance();
			
			List<Method> setters = TypeChecker.getSetters( clazz );
			
			for( Method setter : setters )
			{
				Class<?> setterType = setter.getParameterTypes()[0];
				
				if( setterType.equals( String.class ) )
				{
					setter.invoke( instance, TypeChecker.getFieldName( setter.getName() ) );
				}
				else if( setterType.equals( Boolean.TYPE ))
				{
					setter.invoke( instance, true);
				}
				else
				{
					setter.invoke( instance, new DefaultMaker( setterType ).make() );
				}
			}
			
			return instance;
		} 
		catch (Exception e)
		{
			throw new BruscarException( this.getClass().getName() + " make " + clazz.getName(), e );
		} 
	}
	
	private Object makeList()
	{
		ArrayList result = new ArrayList();
		
		return result;
	}


	public Class<?> getListReturnType( Method method ) 
	{
		Class<?>[] parameters = method.getParameterTypes(); 
		Type returnType = parameters[0];
		
		if(returnType instanceof ParameterizedType)
		{
		    ParameterizedType type = (ParameterizedType) returnType;
		    Type[] typeArguments = type.getActualTypeArguments();
		    Class<?> typeArgClass = (Class<?>) typeArguments[0];
		    return typeArgClass;
		}
		
		return null;

	}
}
